<template>
  <div class="app-container">
    <PageTools type="info">
      <template #before>
        <span>{{ total }}条数据</span>
      </template>
      <template #after>
        <el-button v-permission="'import_excel1'" size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
        <el-button size="small" type="danger" @click="handleExport">导出</el-button>
        <el-button size="small" type="primary" @click="addEmployee">新增员工</el-button>
      </template>
    </PageTools>
    <!-- 放置表格和分页 -->
    <el-card>
      <el-table v-loading="loading" border :data="list">
        <el-table-column label="序号" sortable="" width="80" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template slot-scope="{ row }">
            <img
              v-imgerror="require('@/assets/bigUserHeader.png')"
              :src="row.staffPhoto"
              alt=""
              style="width: 80px; height: 80px; border-radius: 50%;"
              @click="showErDialog(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatterEmployment" />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" sortable="">
          <template slot-scope="{row}">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" prop="enableState">
          <!-- 用value绑定只作为展示效果，不能修改 -->
          <template slot-scope="{ row }">
            <el-switch
              :value="row.enableState === 1"
              active-color="orange"
              inactive-color="grey"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push({ name: 'detail', params: { id: row.id }})">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="handlerDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <!-- page-sizes 设置一个页面显示几条 -->
        <!-- total 是数据总数 -->
        <!-- page-size 当前页数据条数，.sync后页码改变也会同步变 -->
        <!-- current-page 当前页数 -->
        <!-- current-change 页码改变触发 -->
        <!-- size-change 一页显示个数改变时触发 -->
        <el-pagination
          layout="total, sizes, prev, pager, next"
          background
          :total="total"
          :page-sizes="[2,5,10,15]"
          :page-size.sync="page.size"
          :current-page.sync="page.page"
          @current-change="getWorkerList"
          @size-change="getWorkerList"
        />
      </el-row>
    </el-card>
    <add-employee :dialog-visible.sync="dialogVisible" />
    <el-dialog title="头像二维码" :visible.sync="ercodeDialog">
      <canvas id="canvas" ref="ercodeDialog" />
    </el-dialog>
    <assign-role ref="AssignRole" :show-role-assign.sync="showRoleAssign" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import { getUserDetailByidApi } from '@/api/user'
import employeesEmus from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee.vue'
import enumerate from '@/api/constant/employees'
import QrCode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
import { getRoleApi } from '@/api/setting'
export default {
  name: 'EmployeesIndex',
  components: { AddEmployee, AssignRole },
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false, // 控制加载中
      dialogVisible: false, // 弹窗显隐控制器
      ercodeDialog: false, // 控制二维码弹窗显示
      showRoleAssign: false, // 控制角色分配弹框显隐
      userId: '' // 当前员工id
    }
  },
  created() {
    this.getWorkerList()
  },
  methods: {
    // 获取员工列表信息
    async getWorkerList() {
      try {
        this.loading = true
        const { rows, total } = await getEmployeeListApi(this.page)
        this.list = rows // 列表
        this.total = total // 员工总数
      } finally {
        this.loading = false
      }
    },
    formatterEmployment(row, column, cellValue) {
      // row是当前这行数据
      // column是表格一些信息
      // cellValue是当前单元格信息
      // 通过id去匹配配置项的对象，拿到对象去返回它数值对应的内容
      const hireTypeObj = employeesEmus.hireType.find(ele => ele.id === +cellValue)
      return hireTypeObj && hireTypeObj.value || '非正式'
    },
    // 新增员工
    addEmployee() {
      this.dialogVisible = true
    },
    // 点击删除触发
    async handlerDel(row) {
      try {
        await this.$confirm('确定要删除吗？', '提示', { type: 'warning' })
        // 掉接口
        await delEmployeeApi(row.id)
        // 提示删除成功
        this.$message.success('删除成功')
        // 刷新视图
        this.getWorkerList()
      } catch (error) {
        console.log(error)
      }
    },
    handleExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployeeListApi({
          page: 1,
          size: 10000000
        })
        // 请求拿到全部数组对象
        // 但拿到的数组每一项都包含着不需要的字段,一次要根据我们需要字段的数组进行剔除
        // map遍历请求数组
        const newArr = rows.map(ele => {
          const itemArr = [] // 建立一个空数组
          // 拿到所需字段数组进行遍历
          Object.values(headers).forEach(item => {
            // item代表每一个需要字段
            // 如果是时间字段需要进行格式化处理
            if (item === 'timeOfEntry' || item === 'correctionTime') {
              // console.log(this.$options.filters.formatDate(ele[item]))
              itemArr.push(this.$options.filters.formatDate(ele[item]))
            } else if (item === 'formOfEmployment') {
              const tempt = enumerate.hireType.find(ele1 => ele1.id === +ele[item])
              itemArr.push(tempt && tempt.value || '非正式')
            } else {
              itemArr.push(ele[item]) // 将需要字段的值推入数组中
            }
          })
          return itemArr
        })
        console.log(newArr)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: newArr, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '']],
          merges: ['A1:A2', 'B1:G1']
        })
      })
    },
    // 展示二维码弹框
    async showErDialog(info) {
      if (!info) {
        return this.$message.warning('当前员工未设置头像')
      }
      // 显示弹窗
      console.log(this.$refs.ercodeDialog)
      this.ercodeDialog = true
      // 二维码的插件，把信息转换成二维码
      // 下包引入使用插件
      await this.$nextTick()
      QrCode.toCanvas(this.$refs.ercodeDialog, info)
    },
    // 控制角色弹框
    async assignRole(id) {
      const { rows } = await getRoleApi()
      const res = await getUserDetailByidApi(id)
      this.userId = id
      this.$refs.AssignRole.roleList = rows
      this.$refs.AssignRole.roleIds = res.roleIds
      this.showRoleAssign = true
    }
  }
}
</script>

<style lang='scss' scoped>

</style>

